package com.common.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.constant.BalzLogger;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;


public class CaptchaAction extends HttpServlet{
	
	private static final long serialVersionUID = 1L;

	private static BalzLogger logger = new BalzLogger();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doPost(request, response); // if request in method get >> do Post
	}
	 
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

		logger.debug("CaptchaController generate captcha");
		
		byte[] captchaChallengeAsJpeg = null;  
		
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();  
		DefaultManageableImageCaptchaService  captchaService = new DefaultManageableImageCaptchaService();
		
		try{
			String captchaId = request.getSession().getId();   
			logger.debug("captchaId : "+captchaId);
			BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());      
			ImageIO.write(challenge, "jpeg", jpegOutputStream);
		} catch (IllegalArgumentException e) {   
			logger.debug("Generate Captcha Error : "+e.getCause().getMessage());
			response.sendError(HttpServletResponse.SC_NOT_FOUND);     
		} catch (CaptchaServiceException e) {   
			logger.debug("Generate Captcha Error : "+e.getCause().getMessage());
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);     
		}
		
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		// flush it in the response    
		response.setHeader("Cache-Control", "no-store");    
		response.setHeader("Pragma", "no-cache");    
		response.setDateHeader("Expires", 0);    
		response.setContentType("image/jpeg");  
		
		ServletOutputStream responseOutputStream = response.getOutputStream();    
		responseOutputStream.write(captchaChallengeAsJpeg);    
		responseOutputStream.flush();    
		responseOutputStream.close();
		
	}
}
